<template>
	<!-- 商品卡片 -->
	<selectBox @setClass="setClass" :data="data"></selectBox>
	<view :style="{ padding: data.padding + 'px',minHeight: '350rpx'}">
		<!-- 1 100%宽卡片列表-->
		<view v-if="mode === 1 && state.goodsList.length" class="goods-sl-box">
			<view class="goods-box" v-for="item in state.goodsList" :key="item.id"
				:style="[{ marginBottom: data.space * 2 + 'rpx'}]">
				<s-goods-column class="" size="sl" :goodsFields="goodsFields" :tagStyle="tagStyle" :data="item"
					:titleColor="goodsFields.title?.color" :subTitleColor="goodsFields.subtitle.color"
					:topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom"
					@click="sheep.$router.go('/pages/goods/index', { id: item.id })">
					<template v-slot:cart>
						<button class="ss-reset-button cart-btn" :style="[buyStyle]">
							{{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
						</button>
					</template>
				</s-goods-column>
			</view>
		</view>

		<!-- 2   双列瀑布流列表-->
		<view v-if="mode === 2 && state.goodsList.length" class="goods-md-wrap ss-flex ss-flex-wrap ss-col-top">
			<view class="goods-list-box">
				<view class="left-list" :style="[{ paddingRight: data.space + 'rpx', marginBottom: data.space + 'px' }]"
					v-for="item in state.leftGoodsList" :key="item.id">
					<s-goods-column class="goods-md-box" size="md" :goodsFields="goodsFields" :tagStyle="tagStyle"
						:data="item" :titleColor="goodsFields.title?.color" :subTitleColor="goodsFields.subtitle.color"
						:topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom"
						:titleWidth="330 - marginLeft - marginRight"
						@click="sheep.$router.go('/pages/goods/index', { id: item.id })"
						@getHeight="mountMasonry($event, 'left')">
						<template v-slot:cart>
							<button class="ss-reset-button cart-btn" :style="[buyStyle]">
								{{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
							</button>
						</template>
					</s-goods-column>
				</view>
			</view>
			<view class="goods-list-box">
				<view class="right-list" :style="[{ paddingLeft: data.space + 'rpx', marginBottom: data.space + 'px' }]"
					v-for="item in state.rightGoodsList" :key="item.id">
					<s-goods-column class="goods-md-box" size="md" :goodsFields="goodsFields" :tagStyle="tagStyle"
						:data="item" :titleColor="goodsFields.title?.color" :subTitleColor="goodsFields.subtitle.color"
						:topRadius="data.borderRadiusTop" :bottomRadius="data.borderRadiusBottom"
						:titleWidth="330 - marginLeft - marginRight"
						@click="sheep.$router.go('/pages/goods/index', { id: item.id })"
						@getHeight="mountMasonry($event, 'right')">
						<template v-slot:cart>
							<button class="ss-reset-button cart-btn" :style="[buyStyle]">
								{{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
							</button>
						</template>
					</s-goods-column>
				</view>
			</view>
		</view>

		<!-- 3  30%卡片列表-->
		<view v-if="mode === 3 && state.goodsList.length" class="goods-lg-box">
			<view class="goods-box" :style="[{ marginBottom: data.space + 'px' }]" v-for="item in state.goodsList"
				:key="item.id">
				<s-goods-column class="goods-card" size="lg" :goodsFields="goodsFields" :data="item"
					:tagStyle="tagStyle" :titleColor="goodsFields.title?.color"
					:subTitleColor="goodsFields.subtitle.color" :topRadius="data.borderRadiusTop"
					:bottomRadius="data.borderRadiusBottom"
					@tap="sheep.$router.go('/pages/goods/index', { id: item.id })">
					<template v-slot:cart>
						<button class="ss-reset-button cart-btn" :style="[buyStyle]">
							{{ buyNowStyle.mode === 1 ? buyNowStyle.text : '' }}
						</button>
					</template>
				</s-goods-column>
			</view>
		</view>
		<uni-load-more :status="loadState"></uni-load-more>
	</view>
</template>

<script setup>
	/**
	 * 商品模板，装修商品卡片
	 * @description style 1:带tab 2：瀑布流，横向两个，上图下内容 3：大图，横向一个
	 */
	import {
		ref,
		computed,
		reactive,
		onMounted,
		onBeforeUnmount
	} from 'vue';
	import sheep from '@/sheep';
	// import goodsData from './goodsList.js'
	import selectBox from './component/selectBox.vue'
	  import {onLoad,onPullDownRefresh ,onReachBottom} from '@dcloudio/uni-app';
	let pageUrl = ''
	// pageUrl = sheep.$router.getCurrentRoute().fullPath

	const loadState = ref('more')
	
	const state = reactive({
		goodsList: [],
		leftGoodsList: [],
		rightGoodsList: [],
		params:{}
	});
	const page = ref(0);
	const props = defineProps({
		data: {
			type: Object,
			default () {},
		},
		styles: {
			type: Object,
			default () {},
		},
	});
	let defaultValue = JSON.parse(props.data.defaultValue || '{}')

	const {
		mode,
		tagStyle,
		buyNowStyle,
		goodsFields,
		goodsIds
	} = props.data ?? {};
	const {
		marginLeft,
		marginRight
	} = props.styles ?? {};

	// 加载瀑布流
	let count = 0;
	let leftHeight = 0;
	let rightHeight = 0;
  // 下拉刷新
  onPullDownRefresh(() => {
		console.log('下拉刷新');
		restoreGoods()
		getList()
  });	  
	onReachBottom(()=>{
		console.log('触底');
		getList()
	})
	
	let timer;
	let flag;
	function throttle(func, wait = 500, immediate = true) {
	  if (immediate) {
	    if (!flag) {
	      flag = true;
	      // 如果是立即执行，则在wait毫秒内开始时执行
	      typeof func === 'function' && func();
	      timer = setTimeout(() => {
	        flag = false;
	      }, wait);
	    } else {
	    }
	  } else if (!flag) {
	    flag = true;
	    // 如果是非立即执行，则在wait毫秒内的结束处执行
	    timer = setTimeout(() => {
	      flag = false;
	      typeof func === 'function' && func();
	    }, wait);
	  }
	}
	function mountMasonry(height = 0, where = 'left') {
		if (!state.goodsList[count]) return;
		if (where === 'left') leftHeight += height;
		if (where === 'right') rightHeight += height;
		if (leftHeight <= rightHeight) {
			state.leftGoodsList.push(state.goodsList[count]);
		} else {
			state.rightGoodsList.push(state.goodsList[count]);
		}
		count++;
	}


	console.log('defaultValue', defaultValue);
	// console.log('goodsData', goodsData);
	const setClass = (e) => {
		state.params={
			...state.pasams,
			...e,
		}
		console.log('改变了分了类');
		restoreGoods()
		getList()
	}
	async function getGoodsListByIds(ids) {
		let {
			data
		} = await sheep.$api.goods.ids({
			ids
		});
		return data;
	}

	const restoreGoods = () => {
		loadState.value='more'
		count = 0
		page.value=0
		leftHeight = 0;
		rightHeight = 0;
		// state.goodsList = []
		state.leftGoodsList = []
		state.rightGoodsList = []
	}
	const getList = ()=>{
		throttle(getGoodsList,300);
	}
	async function getGoodsList() {
		// uni.showLoading({
		// 	title: '加载中...'
		// })
		if(loadState.value=='no-more')return 
		loadState.value='loading'
		// console.log('接口返回值---------------');
		let res= await sheep.$api.goods.list({
			page:page.value + 1,
			...state.params,
			...defaultValue
			})
			let data =res.data
			// console.log('接口返回值---------------',res.data);
			if(!res.error){
				page.value = data.current_page
				// console.log('接口返回值',res);
				if(page.value>1){
						state.goodsList = state.goodsList.concat(data.data)
				}else{
					state.goodsList = data.data
				}
				if(data.data.length==data.per_page){
					if (mode === 2) {
						mountMasonry();
					}
					// uni.hideLoading()
					loadState.value='more'
				}else{
					loadState.value='no-more'
				}
			
			}
	}

	onLoad(() => {
		getList()
		// state.goodsList = await getGoodsListByIds(goodsIds.join(','));
		// if (mode === 2) {
		//   mountMasonry();
		// }
	});
	// onBeforeUnmount(() => {
	// 	uni.$off([pageUrl + 'indexReachBottom', pageUrl + 'indexPullDownRefresh'])
	// })


	// 购买按钮样式
	const buyStyle = computed(() => {
		if (buyNowStyle.mode == 1) {
			// button
			return {
				background: `linear-gradient(to right, ${buyNowStyle.color1}, ${buyNowStyle.color2})`,
			};
		}

		if (buyNowStyle.mode == 2) {
			// image
			return {
				width: '54rpx',
				height: '54rpx',
				background: `url(${sheep.$url.cdn(buyNowStyle.src)}) no-repeat`,
				backgroundSize: '100% 100%',
			};
		}
	});
</script>

<style lang="scss" scoped>
	.goods-md-wrap {
		width: 100%;
	}

	.goods-list-box {
		width: 50%;
		box-sizing: border-box;

		.left-list {
			&:nth-last-child(1) {
				margin-bottom: 0 !important;
			}
		}

		.right-list {
			&:nth-last-child(1) {
				margin-bottom: 0 !important;
			}
		}
	}

	.goods-box {
		&:nth-last-of-type(1) {
			margin-bottom: 0 !important;
		}
	}

	.goods-md-box,
	.goods-sl-box,
	.goods-lg-box {
		position: relative;

		.cart-btn {
			position: absolute;
			bottom: 18rpx;
			right: 20rpx;
			z-index: 11;
			height: 50rpx;
			line-height: 50rpx;
			padding: 0 20rpx;
			border-radius: 25rpx;
			font-size: 24rpx;
			color: #fff;
		}
	}
</style>